<script lang="ts" setup>
import mcht from '@/api/mcht'
import { useAppStore, useHomeStore } from '@/store'
import { throttle } from '@/utils/shared.ts'

const {
  windowHeight,
  customBarHeight,
} = storeToRefs(useAppStore())
const { mchtNo, modifyEmployee, bit8, roleFlag } = storeToRefs(useHomeStore())
const ruleForm = ref()
const form = reactive({
  mchtNo: mchtNo.value,
  employeeName: '',
  phoneNumber: '',
  roleFlag: '',
})

const roleOptions = [
  { value: '00', text: '商户管理员' },
  { value: '01', text: '商户员工' },
  { value: '02', text: '门店店长' },
  { value: '03', text: '门店员工' },
  { value: '04', text: '商户业务主管' },
]

function roleName(role: string) {
  return {
    '00': '商户管理员',
    '04': '商户业务主管',
    '01': '商户员工',
    '02': '门店店长',
    '03': '门店员工',
  }[role]
}

const rules = {
}

const total = ref(0)
const page = ref(1)
const list = ref([])
const pageSize = ref(5)
const loading = ref<boolean>(false)
const end = ref<boolean>(false)


function resetList() {
  list.value = []
  total.value = 0
  page.value = 1
  end.value = false
}
// onMounted(() => {
//   resetList()
//   query(1)
// })
onShow(() => {
  resetList()
  query(1)
})

const throttledGetList = throttle(getList, 600)

async function query() {
  // list.value = []
  // getList(1)
  throttledGetList(1)
}

async function getList(p: number) {
  const { data } = await mcht.getStaffList(Object.assign(form, {
    pageNum: p,
    pageSize: pageSize.value,
  }))
  if (data?.status === 'success') {
    total.value = data.data.total
    page.value = data.data.pageNum

    let lists = data.data.employeeList
    lists.forEach((e) => {
      let permission = []
      // 店长不能修改和删除自己
      // 商户管理员不能修改和删除自己
      // 商户管理员不能修改和删除门店店长
      permission[0] = (roleFlag.value === '02' && e.roleFlag === '02') || (roleFlag.value === '00' && e.roleFlag === '00') || (roleFlag.value === '00' && e.roleFlag === '02') ? '0' : '1' // 修改
      permission[1] = (roleFlag.value === '02' && e.roleFlag === '02') || (roleFlag.value === '00' && e.roleFlag === '00') || (roleFlag.value === '00' && e.roleFlag === '02') ? '0' : '1' // 删除
      e.permissionArr = permission
      e.fristName = e.employeeName.charAt(0)
    })

    list.value = list.value.concat(lists)

    if (page.value * pageSize.value >= total.value) {
      end.value = true
    }
    else {
      end.value = false
    }
  }
}

function scrolltolower() {
  if (!end.value) {
    getList(page.value + 1)
  }
}

function add() {
  hide_popup()
  uni.navigateTo({
    url: '/pages/home/staff/modify',
  })
}

function modify(employee: any) {
  modifyEmployee.value = employee
  uni.navigateTo({
    url: `/pages/home/staff/modify?employeeNo=${employee.employeeNo}&mode=modify`,
  })
}
function unbind(employee: any) {
  modifyEmployee.value = employee
  uni.navigateTo({
    url: `/pages/home/staff/modify?employeeNo=${employee.employeeNo}&mode=unbind`,
  })
}
function bind(employee: any) {
  modifyEmployee.value = employee
  uni.navigateTo({
    url: `/pages/home/staff/modify?employeeNo=${employee.employeeNo}&mode=bind`,
  })
}
function del(employee: any) {
  uni.showModal({
    title: '删除确认',
    content: `您是否要删除 ${employee.employeeName} 该名员工？`,
    success: async (res) => {
      if (res.confirm) {
        const { data } = await mcht.deleteStaff(mchtNo.value, employee.employeeNo)
        if (data.status === 'success') {
          uni.showToast({
            title: data.message,
          })
          list.value = []
          page.value = 1
          await getList(1)
        }
      }
      else if (res.cancel) {
        // console.log('用户点击取消')
      }
    },
  })
}




const popupMask = ref<boolean>(false)
const popupContainer = ref<boolean>(false)
const searchKey = ref<string>('全部')

function show_popup() {
  popupMask.value = true
  popupContainer.value = true
}

function hide_popup() {
  popupMask.value = false
  popupContainer.value = false
}

function searchList() {
  let result = [form.employeeName, form.phoneNumber, roleName(form.roleFlag) ] 
    .filter(item => item) 
    .join('/');
  if (!result){
    result = '全部'
  }
  searchKey.value = result
  resetList()
  query(1)
  hide_popup()
}
function clearSearchList() {
  resetForm()
  searchKey.value = '全部'
  resetList()
  query(1)
}

function resetForm() {
  form.employeeName = ''
  form.phoneNumber = ''
  form.roleFlag = ''
}

</script>

<template>
  <div class="staff">

    <!-- 弹出框结构 -->
    <div class="li-popup">
      <div class="popup-mask" :class="popupMask ? 'popup-mask-show' : ''" @click="hide_popup">
      </div>
      <div class="popup-container" :class="popupContainer ? 'popup-container-show' : ''">
        <div class="popup-content">
          <div class="popup-body">
            <nut-form ref="ruleForm" :model-value="form" :rules="rules">
              <nut-form-item label="员工姓名" prop="employeeName">
                <nut-input v-model="form.employeeName" class="nut-input-text" placeholder="请输入员工姓名" type="text" />
              </nut-form-item>
              <nut-form-item label="员工手机号" prop="phoneNumber">
                <nut-input v-model="form.phoneNumber" class="nut-input-text" placeholder="请输入员工手机号" type="text" />
              </nut-form-item>
              <nut-form-item label="员工角色" prop="roleFlag">
                <option-select v-model="form.roleFlag" title="员工角色" :options="roleOptions" />
              </nut-form-item>
            </nut-form>
            <div class="li-searchBar-btn">
              <div class="li-cz shake_o" @click="resetForm">重置</div>
              <!-- <div class="li-xz shake_o" @click="add">新增</div> -->
              <div class="li-ss shake_o" @click="searchList">搜索</div>
            </div>
          </div>
        </div>
      </div>
    </div>

      <movable-area class="movable-area" v-if="roleFlag !== '04'">
        <movable-view class="movable-view" x="1000" y="1000" direction="all">
          <view class="newProblem shake_o" @click="add">
            <div class="i-ri:add-fill" style="font-size: 40rpx"></div>
            <div style="font-size: 26rpx;">新增</div>
          </view>
        </movable-view>
      </movable-area>

    <div class="query">

      <div class="li-searchBar">
        <div class="li-rantangle">
          <div class="li-btnleft li-butStyle" :class="searchKey !== '全部' ? 'li-lftactive' : ''"
            @click="clearSearchList">
            <div class="li-texts">{{ searchKey }}</div>
          </div>
          <div class="li-btnright li-butStyle" :class="searchKey !== '全部' ? 'li-ritactive' : ''" @click="show_popup">筛选
          </div>
        </div>
      </div>
      <div style="width: 100%;height: 120rpx;"></div>

    </div>
    <div class="list">
      <template v-if="list.length > 0">
        <scroll-view scroll-y :style="{ height: `${windowHeight - customBarHeight - 40 - 40}px` }"
          @scrolltolower="scrolltolower">

          <div class="li-card-item shake_o shadow" v-for="(employee, index) in list" :key="index">
            <div class="content-box1" :class="employee.statusDesc === '注销' ? 'b-c2' :'b-c1'">
              <div class="cb-lft">
                <div class="first">{{ employee.fristName }}</div>
                <div class="info">
                  <div class="name">{{ employee.employeeName }}</div>
                  <div class="id">{{ employee.employeeNo }}</div>
                </div>
              </div>
              <div class="cb-rit" :class="employee.statusDesc === '注销' ? 'c2' : 'c1'">{{ employee.statusDesc }}
              </div>
            </div>
            <div class="content-box2">
              <div class="item">
                <div class="lable">手机号</div>
                <div class="name">{{ employee.phoneNumber }}</div>
              </div>
              <div class="item">
                <div class="lable">所属门店</div>
                <div class="name">{{ employee.storeNm }}</div>
              </div>
              <div class="item">
                <div class="lable">员工角色</div>
                <div class="name">{{ roleName(employee.roleFlag) }}</div>
              </div>
            </div>
            <div class="content-btn" v-if="employee.statusDesc !== '注销' && employee.mchtNo === form.mchtNo">
              <div class=" c-btn" style="background-color: #2196f3"
              v-if="bit8[1] === '1' && employee.permissionArr[0] === '1'" @click="modify(employee)">修改</div>
            <div class="c-btn" style="background-color: #2196f3" v-if="employee.qrCodeNo && bit8[4] === '1'"
              @click="unbind(employee)">解绑</div>
            <div class="c-btn" style="background-color: #2196f3" v-else-if="bit8[3] === '1'" @click="bind(employee)">
              绑定
            </div>
            <div class="c-btn" style="background-color: #eb0909"
              v-if="bit8[2] === '1' && employee.permissionArr[1] === '1'" @click="del(employee)">删除</div>
          </div>
  
          <div style="padding-bottom: 10rpx;"></div>
    </div>

    <div v-if="end" class="end">没有更多数据了</div>
    <div v-if="loading" class="loading">
      <nut-icon name="loading" />
      数据加载中...
    </div>
    </scroll-view>
</template>
<nut-empty v-else description="暂无数据" />
</div>
</div>
</template>

<route lang="json">{
  "layout": "home",
  "style": {
    "navigationBarTitleText": "员工列表",
    "backgroundColorContent": "#f1f1f1"
  }
}</route>

<style lang="sass" scoped>
.list
  padding: 20rpx
  .item
    background-color: #fff
    border-radius: 6px
    margin-bottom: 15px
    .top
      display: flex
      justify-content: space-between
      border-bottom: 1px solid #e8e8e8
      padding: 10px 13px
      .title
        color: #8e8e8e
      .right
        color: #2196F3
    .content
      display: flex
      justify-content: space-between
      padding: 12px 18px 0
      .left
        .line
          margin-bottom: 12px
          .key
            display: inline-block
            margin-right: 12px
          .value
            display: inline-block
      .right
        .mod
          margin-bottom: 10px
  .end
    text-align: center
    color: #8e8e8e

/* 筛选按钮相关 end */
:deep(.nut-cell-group__wrap)
  box-shadow: none!important
  margin: 0!important
  padding: 10rpx 0!important

:deep(.nut-cell-group .nut-cell::after)
  border-bottom: none
</style>
